define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template'], function ($, undefined, Backend, Table, Form, Template) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'weixin/news/index' + location.search,
                    add_url: 'weixin/news/add',
                    edit_url: 'weixin/news/edit',
                    del_url: 'weixin/news/del',
                    multi_url: 'weixin/news/multi',
                    table: 'weixin_news',
                }
            });

            var table = $("#table");
            Template.helper("Moment", Moment);
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                templateView: true,
                //禁用默认搜索
                search: false,
                //启用普通表单搜索
                commonSearch: true,
                //可以控制是否默认显示搜索单表,false则隐藏,默认为false
                searchFormVisible: false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), operate:false},
                        {field: 'cate_name', title: __('Cate_name')},
                        {field: 'image', title: __('Image'), operate:false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'url', title: __('Url'), operate:false, formatter: Table.api.formatter.url},
                        {field: 'sort', title: __('Sort'), operate:false},
                        {field: 'status', title: __('Status'), searchList: {"normal":__('Normal'),"hidden":__('Hidden')}, formatter: Table.api.formatter.status},
                        {field: 'parent_id', title: __('Parent_id'), operate:false},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.act();
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.act();
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("#data-form"));
                Form.api.bindevent($("#add-form"), function(data, ret){
                    //如果我们需要在提交表单成功后做跳转，可以在此使用location.href="链接";进行跳转
                    Toastr.success("成功");
                }, function(data, ret){
                    //Toastr.success("失败");
                }, function(success, error){
                    //bindevent的第三个参数为提交前的回调
                    //如果我们需要在表单提交前做一些数据处理，则可以在此方法处理
                    //注意如果我们需要阻止表单，可以在此使用return false;即可
                    //如果我们处理完成需要再次提交表单则可以使用submit提交,如下
                    //Form.api.submit(this, success, error);
                    //return false;
                });
            },
            form2JsonString: function(){
                var paramArray = $("#data-form").serializeArray();
                /*请求参数转json对象*/
                var jsonObj={};
                $(paramArray).each(function(){
                    jsonObj[this.name]=this.value;
                });
                // json对象再转换成json字符串
                return JSON.stringify(jsonObj);
            },
            act: function(){
                //选中
                $(".news-box").on("click", ".newsrow", function () {
                    $('.active').removeClass('active');
                    $(this).addClass('active');
                    var index = $(this).find('input').data('id');
                    var data = $.parseJSON($(this).find('input').val());
                    $(this).find('.newsrow-title').text(data.cate_name);
                    $(this).find('img').attr('src', data.image);
                    var html = '<li class="col-xs-3"><a href="' + data.image + '" data-url="' + data.image + '" target="_blank" class="thumbnail"><img onerror="this.src=\'/assets/addons/weixin/images/image.png\'" src="' + data.image + '" class="img-responsive"></a><a href="javascript:;" class="btn btn-danger btn-xs btn-trash"><i class="fa fa-trash"></i></a></li>';
                    $('#p-image').html('').append(html);
                    $("input[name='image']").val(data.image);
                    $("input[name='cate_name']").val(data.cate_name);
                    $("textarea[name='description']").val(data.description);
                    $("input[name='url']").val(data.url);
                    $("input[name='sort']").val(data.sort);
                    $("input[name='id']").val(data.id);
                    $(".select_index").val(index);
                });
                $('.newsrow:first').trigger("click");

                //删除
                $(".news-box").on("click", ".newsrow-del", function () {
                    var _this = this;
                    var id = $(_this).attr('data-id');
                    if (id) {
                        layer.confirm("确定删除此项？", function () {
                            layer.close(1);
                            Fast.api.ajax({
                                url: 'weixin/news/del/ids/' + id
                            }, function (data, ret) {
                                if ((ret.code == 1)) {
                                    $(_this).parent().remove();
                                    $('.newsrow:first').trigger("click");
                                }
                            });
                        });
                    } else {
                        $(_this).parent().remove();
                        $('.newsrow:first').trigger("click");
                    }
                });

                //添加
                $('.add-news-items').click(function () {
                    var index = Math.ceil(Math.random() * 9999999999);
                    var html = '<div>' +
                        '<div class="operation-item newsrow-del">' +
                        '<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>' +
                        '</div>' +
                        '<div class="newsrow news-item-title transition news-image list_' + index + '" style="margin-bottom: 15px">' +
                        '<input class="list_' + index + '" type="hidden" name="list[' + index + ']" value=\'{"cate_name":"","description":"","image":"","url":"","sort":"0"}\' data-id="' + index + '">' +
                        '<div class="right-text newsrow-title"></div>' +
                        '<img class="left-image" onerror="this.src=\'/assets/addons/weixin/images/image.png\'" src=""/>' +
                        '</div>' +
                        '</div>';
                    $(".news-box").append(html);
                });

                //表单数据更新
                $("input[name='cate_name']").on("input propertychange", function () {
                    var index = $('.select_index').val();
                    $('.list_' + index).parent().find('.newsrow-title').text($(this).val());
                });
                $("#p-image").on("DOMNodeInserted", function () {
                    var index = $('.select_index').val();
                    $('.list_' + index).parent().find('img').attr('src', $("input[name='image']").val());
                    $('.list_' + index).val(Controller.api.form2JsonString());
                });
                $("input,textarea").on("input propertychange", function () {
                    var index = $('.select_index').val();
                    $('.list_' + index).val(Controller.api.form2JsonString());
                });
            }
        }
    };
    return Controller;
});